import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import traceback


class jiaMiPass:
    def getpassword(self, password, Rsa_Token):
        try:
            print("开始进行用户密码加密")

            # 1. 增强参数合法性检查
            if Rsa_Token is None:
                raise ValueError("RSA_Token不能为None")
            if not isinstance(Rsa_Token, (str, bytes)):
                raise TypeError(f"RSA_Token应为字符串或字节类型，实际类型: {type(Rsa_Token)}")

            # 2. 优化Base64解码处理
            try:
                decoded_token = base64.b64decode(Rsa_Token)  # 解码并保存结果
            except (base64.binascii.Error, TypeError) as decode_error:
                error_msg = f"RSA_Token格式错误: {str(decode_error)}"
                print(error_msg)
                raise ValueError(error_msg) from decode_error

            # 3. 公钥处理
            try:
                public_key_str = decoded_token.decode('utf-8')  # 使用已解码的结果
                print(f"RSA_Token解码后的公钥内容：{public_key_str}")

                pubkey = RSA.importKey(public_key_str)
                print(f"导入的公钥属性信息：{pubkey.export_key().decode('utf-8')}")

                # 4. 密码加密
                cipher = PKCS1_v1_5.new(pubkey)
                encrypted_password = cipher.encrypt(password.encode('utf-8'))
                ciphertext = base64.b64encode(encrypted_password).decode('utf-8')
                print(f"用户密码加密串：{ciphertext}")

                return ciphertext

            except (ValueError, RSA.Error) as key_error:
                error_msg = f"公钥处理失败: {str(key_error)}"
                print(error_msg)
                raise RuntimeError(error_msg) from key_error

        except Exception as e:
            # 5. 修复异常日志记录
            print(f"用户密码加密失败，错误类型: {type(e).__name__}, 错误信息: {str(e)}")
            print("详细错误堆栈:")
            traceback.print_exc()  # 正确打印完整堆栈信息
            raise  # 重新抛出原始异常